Ext.extend(app.module,{
    currentFormValues: {},
    init: function(){
        this.ds = new Ext.data.Store({
            proxy: new Ext.data.HttpProxy({url:'paper/papers.do'}),
            reader: new Ext.data.JsonReader({
                totalProperty: 'total',
                root: 'rows',
                idProperty: 'id'
            },[
                {name:'id'},
                {name:'name'},
                {name:'kemuid'},
                {name:'kemuname'},
                {name:'state'},
                {name:'addtime'},
                {name:'starttime'},
                {name:'kstime'}
            ])
        });
        main = this;
        this.sm = new Ext.grid.CheckboxSelectionModel();
        this.body = new Ext.grid.GridPanel({
            store: this.ds,
            region: 'center',
            loadMask: true,
            viewConfig:{
                forceFit:true
            },
            sm: this.sm,
            columns: [
                new Ext.grid.RowNumberer(),
                this.sm,
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'name',
                    header: '试卷名称'
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'kemuid',
                    hidden: true
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'kemuname',
                    header: '科目'
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'state',
                    header: '状态',
                    renderer: function(value){
                        if (value==0){
                            return "等待审核";
                        } else if(value==1){
                            return "等待开始";
                        } else if (value==2) {
                            return "考试正在进行";
                        } else if (value==3){
                            return "考试已结束";
                        } else {
                            return "";
                        }
                    }
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'addtime',
                    header: '添加时间'
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'starttime',
                    header: '开始时间'
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'kstime',
                    header: '考试时间'
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'id',
                    header: '操作',
                    renderer: function(value,cellmeta,record,rowIndex,columnIndex,store){
                        var state = record.data.state;
                        if (state==0){
                            return "<input type='button' value='审核通过' onclick='main.changePaper("+value+","+state+","+"\"确定审核通过？\""+");' />";
                        } else if(state==1){
                            return "<input type='button' value='开始考试' onclick='main.changePaper("+value+","+state+","+"\"确定考试开始？\""+");' />";
                        } else if (state==2) {
                            return "<input type='button' value='结束考试' onclick='main.changePaper("+value+","+state+","+"\"确认将结束考试，将不能再进入和上传？\""+");' />";
                        } else {
                            return "";
                        }
                    }
                }
            ],
            tbar: {
                xtype: 'toolbar',
                items: [
                    {
                        text: '新增',
                        iconCls : 'btn-new',
                        scope: this,
                        handler: this.add
                    },
                    {
                        xtype: 'tbseparator'
                    },
                    {
                        text: '删除',
                        iconCls : 'btn-del',
                        scope: this,
                        handler: this.del
                    },
                    {
                        xtype: 'tbseparator'
                    },
                    {
                        text: '计算客观题成绩',
                        iconCls : 'btn-edit',
                        scope: this,
                        handler: function(){
                            var recs = this.body.getSelectionModel().getSelections();
                            if (recs.length==0) {
                                Ext.Msg.alert('信息', '请选择要试卷。');
                            } else if(recs.length>1) {
                                Ext.Msg.alert('信息', '只能选择一个试卷。');
                            } else {
                                Ext.Msg.confirm('计算', '确认将开始计算？将会耗费较多服务器资源',
                                    function(btn) {
                                        if (btn == 'yes') {
                                            Ext.Ajax.request({
                                                method:'POST',
                                                url: 'score/countMark.do',
                                                params: {id:recs[0].data.id},
                                                disableCaching: true,   //禁用缓存
                                                scope: this,
                                                success: function(response){
                                                    var json = Ext.util.JSON.decode(response.responseText);
                                                    if(!(json.info==undefined || json.info=='')){
                                                        Ext.Msg.alert('提示', json.info);
                                                    }
                                                },
                                                failure: function(form, action) {
                                                    var info = action.result.info;
                                                    Ext.Msg.alert('提示', info);
                                                }
                                            });
                                        }
                                    }
                                );
                            }
                        }
                    }
                ]
            },
            bbar: {
                xtype: 'paging',
                pageSize: 15,
                displayInfo: true,
                store: this.ds
            }
        });
        this.main.add(this.body);
        this.main.doLayout();
        this.ds.load({
            params: {start:0, limit:15 }
        });
        this.render();
    },
    getDialog: function(){
        var dlg = new Ext.Window({
            height: 400,
            width: 400,
            layout: 'fit',
            border: false,
            frame: true,
            title: '',
            closeAction: 'hide',
            modal: true,
            plain: true,
            resizable: false,
            items: [this.form],
            listeners: {
                scope: this,
                render: function(fp){
                    this.form.getForm().waitMsgTarget = fp.getEl();
                },
                show: function(){
                    var f = this.form.getForm();
                    f.setValues(this.currentFormValues);
                    f.clearInvalid();
                }
            }
        });
        return dlg;
    },
    getForm: function() {
        var kemuStore = new Ext.data.Store({
            proxy: new Ext.data.HttpProxy({url:'kemu/getAllKemus.do'}),
            reader: new Ext.data.JsonReader({
                root: 'rows',
                idProperty: 'id'
            },[
                {name:'id'},
                {name:'name'}
            ])
        });
        var comboKemu = new Ext.form.ComboBox({
            store: kemuStore,
            editable: false,
            emptyText: '请选择科目...',
            allowBlank: false,
            mode: 'remote',
            hiddenName : 'kemuid',
            typeAhead : true,
            triggerAction : 'all',
            displayField: 'name',
            valueField: 'id',
            fieldLabel: '科目'
        });
        var form = new Ext.form.FormPanel({
            defaultType: 'textfield',
            bodyStyle: 'padding:5px',
            buttonAlign: 'center',
            url:'paper/save.do',
            labelWidth: 120,
            defaults: {
                anchor: '90%'
            },
            items: [
                {
                    xtype: 'hidden',
                    name: 'id',
                    fieldLabel: 'Label'
                },
                comboKemu,
                {
                    xtype: 'textfield',
                    name: 'name',
                    allowBlank: false,
                    emptyText: '试卷名称不能为空',
                    fieldLabel: '试卷名称'
                },
                {
                    xtype: 'textfield',
                    name: 'danxuan',
                    emptyText: '请输入单选题数量...',
                    fieldLabel: '单选题数量'
                },
                {
                    xtype: 'textfield',
                    name: 'duoxuan',
                    emptyText: '请输入多选题数量...',
                    fieldLabel: '多选题数量'
                },
                {
                    xtype: 'textfield',
                    name: 'panduan',
                    emptyText: '请输入判断题数量...',
                    fieldLabel: '判断题数量'
                },
                {
                    xtype: 'textfield',
                    name: 'wordCaozuo',
                    emptyText: '请输入Word操作题数量...',
                    fieldLabel: 'word数量'
                },
                {
                    xtype: 'textfield',
                    name: 'excelCaozuo',
                    emptyText: '请输入excel操作题数量...',
                    fieldLabel: 'excel数量'
                },
                {
                    xtype: 'textfield',
                    name: 'powerpointCaozuo',
                    emptyText: '请输入powerpoint操作题数量...',
                    fieldLabel: 'ppt数量'
                },
                {
                    xtype: 'textfield',
                    id: 'starttime',
                    name: 'starttime',
                    hidden: true
                },
                {
                    xtype: 'datefield',
                    fieldLabel: '考试日期',
                    id: 'ksdate',
                    emptyText: '请选择考试日期',
                    format: 'Y-m-d',
                    allowBlank: false
                },
                {
                    xtype: 'compositefield',
                    fieldLabel: '考试开始时间',
                    combineErrors: false,
                    items: [
                        {
                            id: 'kshours',
                            xtype: 'textfield',
                            width: 48,
                            emptyText: '时',
                            allowBlank: false
                        },
                        {
                            xtype: 'displayfield',
                            value: '：'
                        },
                        {
                            id: 'ksminutes',
                            xtype: 'textfield',
                            width: 48,
                            emptyText: '分',
                            allowBlank: false
                        }
                    ]
                },
                {
                    xtype: 'textfield',
                    name: 'kstime',
                    emptyText: '请输入考试时间（分钟）...',
                    fieldLabel: '考试时间（分钟）',
                    allowBlank: false
                }
            ],
            buttons: [{
                text: '确定',
                scope: this,
                handler: function() {
                    this.submit();
                }
            },
                {
                    text: '重置',
                    scope: this,
                    handler: function() {
                        var f = this.form.getForm();
                        f.reset();
                        f.setValues(this.currentFormValues);
                        f.clearInvalid();
                    }
                }]
        });
        return form;
    },
    submit: function(){
        if (this.form.getForm().isValid()) {
            var mydate = Ext.getCmp('ksdate').getValue();
            mydate.setHours(Ext.getCmp('kshours').getValue());
            mydate.setMinutes(Ext.getCmp('ksminutes').getValue());
            Ext.getCmp('starttime').setValue(
                mydate.getFullYear() + "/" + (mydate.getMonth()+1) + "/" + mydate.getDate() + " " +
                Ext.getCmp('kshours').getValue() + ":" + Ext.getCmp('ksminutes').getValue() + ":00"
            );
            this.form.getForm().submit({
                waitTitle: '保存数据',
                waitMsg: '正在保存……',
                scope: this,
                method: 'post',
                params: '',
                submitEmptyText: false,
                success: function(form, action) {
                    var info = action.result.info;
                    if (action.result.success) {
                        this.ds.reload();
                        if (action.result.method == "Create") {
                            //this.form.getForm().reset();
                        } else {
                            this.dlg.hide();
                        }
                    }
                    Ext.Msg.alert('信息', info);
                },
                failure: function(form, action) {
                    var info = action.result.info;
                    Ext.Msg.alert('提示', info);
                }
            });
        }
    },
    add: function() {
        Ext.apply(this.currentFormValues, {
            kemuid: '',
            name: "",
            danxuan: "",
            duoxuan: "",
            panduan: "",
            wordCaozuo: "",
            excelCaozuo: "",
            powerpointCaozuo: "",
            starttime: "",
            kstime: ""
        });
        this.dlg.setTitle("增加试卷");
        this.dlg.show();
    },

    edit: function() {
        var recs = this.body.getSelectionModel().getSelections();
        if (recs.length==0) {
            Ext.Msg.alert('信息', '请选择要编辑的试卷。');
        } else if(recs.length>1) {
            Ext.Msg.alert('信息', '只能选择一个试卷进行编辑。');
        } else {
            this.dlg.setTitle("编辑试卷");
            Ext.apply(this.currentFormValues, {
                id: recs[0].data.id,
                name: recs[0].data.name,
                description: recs[0].data.description
            });
            this.dlg.show();
        }
    },

    del: function() {
        var mainContent = this;
        if (this.body.getSelectionModel().hasSelection()) {
            var recs = this.body.getSelectionModel().getSelections();
            var ids = [];
            var titles = [];
            for (var i = 0; i < recs.length; i++) {
                var data = recs[i].data;
                ids.push(data.id);
                titles.push(data.name);
            }
            Ext.Msg.confirm('删除试卷', '确定删除以下试卷？<br><font color="red">' + titles.toString() + '</font>',
                function(btn) {
                    if (btn == 'yes') {
                        Ext.Ajax.request({
                            method:'post',
                            url:'paper/remove.do',
                            params:{
                                ids:ids.toString()
                            },
                            scope: mainContent,
                            success: function(resp, opts) {
                                var result = Ext.util.JSON.decode(resp.responseText);
                                var info = result.info;
                                if(result.success=='true') {
                                    this.ds.reload();
                                    Ext.Msg.alert('信息', info);
                                }else {
                                    Ext.Msg.alert('信息', info);
                                }
                            },
                            failure: function(resp,opts) {
                                var result = Ext.util.JSON.decode(resp.responseText);
                                var info = result.info;
                                Ext.Msg.alert('提示', info);
                            }
                        });
                    }
                });
        } else {
            Ext.Msg.alert('信息', '请选择要删除的试卷！');
        }
    },
    //改变考试状态
    changePaper: function(id,state,message){
        main = this;
        Ext.Msg.confirm('提示', message,
            function(btn) {
                if (btn == 'yes') {
                    Ext.Ajax.request({
                        method:'POST',
                        url: 'paper/changePaper.do',
                        params: {id:id,state:state},
                        disableCaching: true,   //禁用缓存
                        scope: this,
                        success: function(response){
                            main.ds.reload();
                            var json = Ext.util.JSON.decode(response.responseText);
                            if(!(json.info==undefined || json.info=='')){
                                Ext.Msg.alert('提示', json.info);
                            }

                        },
                        failure: function(form, action) {
                            var info = action.result.info;
                            Ext.Msg.alert('提示', info);
                            this.ds.reload();
                        }
                    });
                }
            }
        );
    },
    render: function() {
        if (!this.form) {
            this.form = this.getForm();
        };
        if (!this.dlg) {
            this.dlg = this.getDialog();
        };
    }
});